<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\energy;

use think\facade\Db;
use app\common\dao\energy\EnergyPlanDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
use app\common\repositories\property\auth\PropertyAuthAccessRepository;

/**
 * Class EnergyPlanRepository
 *
 * @mixin EnergyPlanDao
 */
class EnergyPlanRepository extends BaseRepository
{

    public function __construct(EnergyPlanDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'propertyInfo' => function ($query) {
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    /**
     * 接口获取计费方案
     * @param array $where
     * @param $page
     * @param $limit
     * @param int|null $propertyId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-19 09:52
     */
    public function getApiList(array $where, $page, $limit, int $propertyId = null)
    {
        /** @var PropertyAuthAccessRepository $propertyAuthAccessRepository */
        $propertyAuthAccessRepository = app()->make(PropertyAuthAccessRepository::class);
        $propertyIds = $propertyAuthAccessRepository->getPropertyIdsByUserId($where['add_uid']);
        $query = $this->dao->search($where, $propertyId)
            ->where(function ($query) use ($where, $propertyIds) {
                ## 授权物业
                $query->where('property_id', 'in', $propertyIds);
            });
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'propertyInfo' => function ($query) {
                    $query->bind(['property_name' => 'name']);
                }
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    /**
     * 获取计费方案 呢称
     * @param array $where
     * @param int $propertyId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-07 17:29
     */
    public function getApiPlanData(array $where, int $propertyId)
    {
        /** @var PropertyAuthAccessRepository $propertyAuthAccessRepository */
        $propertyAuthAccessRepository = app()->make(PropertyAuthAccessRepository::class);
        $propertyIds = $propertyAuthAccessRepository->getPropertyIdsByUserId($where['add_uid']);
        $list = $this->dao->getSearch([])
            ->when(isset($where['energy_type']) && $where['energy_type'] !== '', function ($query) use ($where) {
                $query->where('energy_type', intval($where['energy_type']));
            })
            ->where('property_id', 'in', $propertyIds)
            ->where('property_id', $propertyId)
            ->whereOr('add_uid', $where['add_uid'])
            ->field('plan_name label,id value')
            ->select()->toArray();
        return $list;
    }


    public function addInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            if (isset($data['stair_price']) && is_array($data['stair_price'])) {
                $data['stair_price'] = json_encode($data['stair_price'], JSON_UNESCAPED_UNICODE);
            }
            $data['property_id'] = $propertyId;
            $info = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'ENERGY.PLAN.ADD', $data);
            return $info;
        });
    }


    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            if (isset($data['stair_price']) && is_array($data['stair_price'])) {
                $data['stair_price'] = json_encode($data['stair_price'], JSON_UNESCAPED_UNICODE);
            }
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'ENERGY.PLAN.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->where('id', $id)
            ->find();
        return $data;
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        /** @var PropertyUsersLogRepository $repository */
        $repository = app()->make(PropertyUsersLogRepository::class);
        $repository->addInfo($info['property_id'], $userId, 'ENERGY.PLAN.DEL', $info);
        $this->dao->delete($info['id']);
    }


    /**
     * 验证设备管理权限
     * @param int $id
     * @param $userId
     * @return bool
     * @throws \think\db\exception\DbException
     *
     * @author Amos
     * 2024-05-18 17:22
     */
    public function existsByUserId(int $id, $userId)
    {
        return $this->dao->search([])
                ->where(function ($query) use ($userId) {
                    /** @var PropertyAuthAccessRepository $propertyAuthAccessRepository */
                    $propertyAuthAccessRepository = app()->make(PropertyAuthAccessRepository::class);
                    $propertyIds = $propertyAuthAccessRepository->getPropertyIdsByUserId($userId);
                    ## 验证权限
                    $query->where('property_id', 'in', $propertyIds);
                })->where('id', $id)->count() > 0;
    }


    public function getEnergyPlanData(int $propertyId = null, array $where = [])
    {
        $list = $this->dao->search($where, $propertyId)
            ->field('plan_name label,id value')
            ->select()->toArray();
        return $list;
    }
}